<?php
namespace App\Modules\Relationship\Models;


use App\Http\Services\CommonServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Base;

class RsRelationshipLevelModel extends Base {

    protected $table = "rs_relationship_level";
    protected $fields = ['id', 'level', 'level_name as levelName', 'intimate_max as intimateMax',
        'level_img as levelImg', 'content', 'content_url as contentUrl', 'intimate', 'type',
        'upper_limit as upperLimit'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
        $this->tablePrefix = env('DB_PREFIX');
    }

    // 获取某条用等级记录
    public function getOneTypeRecord($type, $level){
        $condition = array(
            "type"=>$type,
            "level"=>$level,
            "is_deleted"=>0
        );
        $return = $this->getOneByCondition($condition, $this->fields);
        if (!$return) {
            throw new \Exception("等级信息不存在");
        }
        return $return;
    }

    // 获取某条用户关系记录
    public function getAllLevelRecord($type){
        $condition = array(
            "type"=>$type,
            "is_deleted"=>0
        );
        $orderBy = array(
            "field"=>'level',
            "sort"=>'asc');
        $return = $this->getListByCondition($condition, $this->fields, $orderBy);
        return $return;
    }

    // 获取某个分值现在的等级
    public function getLevelByIntimate (int $intimate, int $type) {
        $table = $this->tablePrefix . $this->table;
        $fields = implode(',', $this->fields);
        $sql = "select {$fields} from {$table} where intimate<=? and (intimate_max>=? or intimate_max=0) and type = ? and is_deleted = 0";
        $bindings = array($intimate, $intimate,$type);
        $re = DB::select($sql, $bindings);
        if (!$re) {
            return null;
        }
        return self::objToArray($re[0]);
    }

    /**
     * 获取全部分类
     * @param int $type 等级分类 0 1-好友 2-密友 3-CP
     */
    public function getAllLevel ($type = 0, $index_key='idKey') {
        $return = [];
        $table = $this->tablePrefix . $this->table;
        $fields = implode(',', $this->fields);
        if ($type == 0) {
            $typeArr = [1,2,3];
        } else {
            $typeArr = [$type];
        }
        $sql = "select {$fields}, concat(type, '_', level) as idKey from {$table} where type in (" . implode(',', $typeArr) .") and is_deleted = 0";
        $levels = DB::select($sql);
        $levelsArr = self::objToArray($levels);
        if ($levels != null && $index_key && in_array($index_key, ['idKey'])){
            $levelsArr = array_column($levelsArr, null, $index_key);
        }
        return $levelsArr;
    }

}

